import React from 'react'
import {View, TextInput, StyleSheet, TouchableOpacity, Platform, PermissionsAndroid, Text, Image} from 'react-native'
import PropTypes from 'prop-types'
import {Toast} from 'antd-mobile'
import CommonStyle, {size, SCREEN} from '../../assets/styles/index'
import {MyIcon} from '../common/index'
import ImagePicker from 'react-native-image-picker'
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import moment from 'moment'

const options = {
    quality: 1.0,
    maxWidth: 300,
    maxHeight: 300,
    title: '请选择照片',
    cancelButtonTitle: '取消',
    chooseFromLibraryButtonTitle: '从相册中选择',
    takePhotoButtonTitle: '拍照',
    allowsEditing: true,
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
};

class tool extends React.Component {
    constructor() {
        super();
        this.state = {
            currentTime: 0.0,
            recording: false,
            stoppedRecording: false,
            finished: false,
            audioPath: AudioUtils.DocumentDirectoryPath + '/test.aac',
            hasPermission: undefined,
        };

    }


    componentDidMount() {
        this._checkPermission().then((hasPermission) => {
            this.setState({hasPermission});
            if (!hasPermission) {
                Toast.fail('轻生活暂无麦克风权限，请前往系统开启');
                return;
            }

            this.prepareRecordingPath(this.state.audioPath);

            AudioRecorder.onProgress = (data) => {

                if (this.state.recording) {
                    this.setState({currentTime: Number(data.currentTime).toFixed(2)});
                }
            };

            AudioRecorder.onFinished = (data) => {
                if (Platform.OS === 'ios') {
                    this._finishRecording(data.status === "OK", data.audioFileURL);
                }
            };
        });
    }

    //文字发送事件
    onSubmitEditing(e) {
        this.props.onSend({
            type: 'txt',
            data: e.nativeEvent.text
        });
    }

    //图片发送事件
    handleImagePicker() {
        ImagePicker.showImagePicker(options, (response) => {
            console.log('handleImagePicker', response);
            if (response.didCancel) {

            }
            else if (response.error) {

            }
            else if (response.customButton) {

            }
            else {
                let source;  // 保存选中的图片

                if (Platform.OS === 'android') {
                    source = {uri: response.uri, isStatic: true};

                } else {
                    source = {uri: response.uri.replace('file://', ''), isStatic: true};
                }

                this.props.onSend({
                    type: 'img',
                    data: {
                        ext: {
                            file_length: response.fileSize,
                            filename: response.fileName || '',
                            filetype: response.fileName && (response.fileName.split('.')).pop(),
                            width: response.width,
                            height: response.height,
                        },
                        file: {
                            data: {
                                uri: source.uri, type: 'application/octet-stream', name: response.fileName
                            }
                        }
                    }
                });
            }
        })
    }

    /**************************语音相关*********************************/
    //准备录音
    prepareRecordingPath(audioPath) {
        AudioRecorder.prepareRecordingAtPath(audioPath, {
            SampleRate: 22050,
            Channels: 1,
            AudioQuality: "Low",
            AudioEncoding: "aac",
            AudioEncodingBitRate: 32000
        });
    }

    //检查权限
    _checkPermission() {
        if (Platform.OS !== 'android') {
            return Promise.resolve(true);
        }

        const rationale = {
            'title': '麦克风权限',
            'message': '轻生活需要克风权限，请前往系统开启'
        };

        return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, rationale)
            .then((result) => {
                console.log('Permission result:', result);
                return (result === true || result === PermissionsAndroid.RESULTS.GRANTED);
            });
    }


    async _stop() {
        try {
            const filePath = await AudioRecorder.stopRecording();

            if (Platform.OS === 'android') {
                this._finishRecording(true, filePath);
            }
            return filePath;
        } catch (error) {
            console.error(error);
        }
    }

    async _record() {

        if (!this.state.hasPermission) {
            console.warn('Can\'t record, no permission granted!');
            return;
        }
        const audioName = moment().format('x') + '.aac';
        const audioPath = AudioUtils.DocumentDirectoryPath + '/' + audioName;
        this.setState({audioPath});
        this.prepareRecordingPath(audioPath);
        this.setState({recording: true});
        try {
            const filePath = await AudioRecorder.startRecording();
        } catch (error) {
            console.error(error);
        }
    }

    _finishRecording(didSucceed, filePath) {
        this.setState({recording: false});
        this.props.onSend({
            type: 'audio',
            data: {
                file: {
                    data: {
                        uri: filePath,
                        type: 'application/octet-stream',
                        name: filePath.replace(AudioUtils.DocumentDirectoryPath + '/', '').replace('file://', '')
                    }
                }
            }
        });
        console.log(`Finished recording of duration ${this.state.currentTime} seconds at path: ${filePath}`);
    }


    renderRecording() {
        if (this.state.recording) {
            return (
                <View style={Styles.recoding}>
                    <Image source={require('../../assets/image/recording.gif')} style={Styles.recodingImage}
                           resizeMode='stretch' />
                    <Text style={Styles.recodingText}>正在录音:{Number(this.state.currentTime).toFixed(2)}</Text>
                    <Text style={Styles.recodingTips}>松手结束录音并发送!</Text>
                </View>
            )
        }
        return null;
    }

    render() {
        return (
            <View style={Styles.container}>
                <TouchableOpacity style={Styles.btn} onLongPress={this._record.bind(this)}
                                  onPressOut={this._stop.bind(this)}>
                    <MyIcon name='yuyin-copy' size={30} color="rgb(128,130,135)"/>
                </TouchableOpacity>

                <TextInput style={Styles.input}
                           {...this.props}
                           clearTextOnFocus
                           clearButtonMode='while-editing'
                           returnKeyType="send"
                           placeholder={this.props.placeholder}
                           enablesReturnKeyAutomatically
                           underlineColorAndroid="transparent"
                           textAlignVertical='top'
                           accessibilityLabel="输入内容"
                           onSubmitEditing={this.onSubmitEditing.bind(this)}

                />
                <View style={[CommonStyle.centerVH, {flexDirection: 'row', height: '100%'}]}>
                    <TouchableOpacity style={Styles.btn}>
                        <MyIcon name='biaoqing' size={30} color="rgb(128,130,135)"/>
                    </TouchableOpacity>
                    <TouchableOpacity style={Styles.btn} onPress={this.handleImagePicker.bind(this)}>
                        <MyIcon name='tianjia' size={39} color="rgb(128,130,135)"/>
                    </TouchableOpacity>
                </View>
                {this.renderRecording()}
            </View>
        )
    }
}

const Styles = StyleSheet.create({
    container: {
        height: '100%',
        flex: 1,
        backgroundColor: '#ededed',
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        position: 'relative'
    },
    input: {
        flex: 1,
        height: '80%',
        backgroundColor: '#fff',
        marginLeft: 5,
        marginRight: 5,
        borderRadius: 5,
        paddingLeft: 10,
        paddingRight: 5,
    },
    btn: {
        marginLeft: 4,
        marginRight: 4,
    },
    recoding: {
        position: 'absolute',
        width: size(375 * 0.4),
        height: size(375 * 0.4),
        left: (SCREEN.width - size(375 * 0.4)) / 2,
        top: -(SCREEN.height) / 2,
        backgroundColor: 'rgba(0,0,0,0.5)',
        zIndex: 100,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius:10,
    },
    recodingImage:{
        width: size(375 * 0.4*0.6),
        height: size(375 * 0.4*0.6 *(264/408)),
    },
    recodingText:{
        color:'#fff',
        marginRight:10,
        marginTop:10,
        fontSize:14,
    },
    recodingTips:{
        color:'#fff',
        marginTop:10,
        fontSize:14,
    }
});

tool.propTypes = {};

tool.defaultProps = {};
export default tool;